<template>
  <div class="container">
    <div class="banner">
      <img src="../../assets/images/beijingImage.png" alt="Delivery banner" class="banner-image" />
      <img src="../../assets/images/baijiantou.png" alt="" class="banner-return" @click="goback">
    </div>

    <!-- 收取件地址填写 -->
    <div class="address-info">
    <div class="qusong-title">
      <h3>取送件</h3>
      <span>您下订单，我们为您及时取送！</span>
    </div>
    <div class="divider"></div>
    <van-cell-group >
        <van-field
          v-model="pickupAddress"
          name="pickupAddress"
          label="到哪里取件"
          label-align="top"
          placeholder="点击完善收件地址"
          :rules="[{ required: true, message: '请输入取件地址' }]"
        >
          <template #right-icon>
            <van-tag type="primary"  
            @click="openAddressPopup(2)" 
            class="common-use">常用</van-tag>
          </template>
        </van-field>
        <div class="divider"></div>
        <van-field
          v-model="deliveryAddress"
          name="deliveryAddress"
          label="要送到哪里"
          label-align="top"
          placeholder="点击完善收件地址"
          :rules="[{ required: true, message: '请输入送件地址' }]"
        >
          <template #right-icon>
            <van-tag type="primary" 
            @click="openAddressPopup(1)"
            class="common-use">常用</van-tag>
          </template>
        </van-field>
      </van-cell-group>

     
    </div>

    <!-- 联系方式填写 -->
    <div class="address-info">
    <div class="qusong-title">
      <h3>联系方式</h3>
      <span>请留下您的联系方式，以便我们联系您</span>
    </div>
    <div class="divider"></div>
    <van-cell-group >
        <van-field
          v-model="phoneNumber"
          name="phoneNumber"
          label="手机号码"
          label-align="top"
          placeholder="点击填写手机号码"
          :rules="[{ required: true, message: '请输入手机号码' }]"
        >
        <template #right-icon>
            <van-tag type="primary" @click="onSelectPhone" class="common-use">常用</van-tag>
          </template>
        </van-field>
        <div class="divider"></div>
        <van-field
          v-model="otherContact"
          name="otherContact"
          label="其他联系方式"
          label-align="top"
          placeholder="点击完善联系方式"
        />
        
      </van-cell-group>
    </div>
    
    <!-- 快递信息填写 -->
    <div class="order-form">
      <!-- 快递信息 -->
      <div class="header">
      <!-- <van-nav-bar title="快递信息" right-text="规则" /> -->
       <h3 >快递信息</h3>
      <span class="subtitle">...以便我们能够快速找到您的快递...</span>
      </div>
      <!-- 包裹数量 -->
      <van-cell-group inset title="包裹数量">
      <!-- 小件 -->
      <van-cell>
        <template #title>
          <div class="package-title">
            <van-tag type="primary" size="medium">小件</van-tag>
            <span class="package-desc">一个手机盒那么大</span>
          </div>
        </template>
        <template #right-icon>
          <van-stepper v-model="packageCount.small" min="0" />
        </template>
      </van-cell>
      <!-- 中件 -->
      <van-cell>
        <template #title>
          <div class="package-title">
            <van-tag type="warning" size="medium">中件</van-tag>
            <span class="package-desc">两个手机盒那么大</span>
          </div>
        </template>
        <template #right-icon>
          <van-stepper v-model="packageCount.medium" min="0" />
        </template>
      </van-cell>
      <!-- 大件 -->
      <van-cell>
        <template #title>
          <div class="package-title">
            <van-tag type="danger" size="medium">大件</van-tag>
            <span class="package-desc">
              个人的力量可能不太够了
              <br />
              (多发小件，联系客服更合理)
            </span>
          </div>
        </template>
        <template #right-icon>
          <van-stepper v-model="packageCount.large" min="0" />
        </template>
      </van-cell>
      </van-cell-group>

      <!-- 取件码 -->
      <van-cell-group inset class="mt-3">
      <van-field
        v-model="pickupCode"
        label="取件码"
        placeholder="点击输入取件码"
      >
        <template #button>
          <van-button size="small" type="primary" @click="verifyCode">
            自动识别
          </van-button>
        </template>
      </van-field>

      <!-- 上传图片 -->
      <van-cell title="上传图片">
        <template #right-icon>
          <van-uploader v-model="fileList" :max-count="1" @after-read="onAfterRead"/>
        </template>
      </van-cell>
      <van-cell>
        <div class="total-packages">
          累计包裹：{{ totalPackages }}
        </div>
      </van-cell>
      </van-cell-group>

      <!-- 备注留言 -->
      <van-cell-group inset class="mt-4">
      <van-field
        v-model="remarks"
        label="备注留言"
        type="textarea"
        placeholder="点击填写写您的需求"
        rows="3"
        autosize
      />
      </van-cell-group>
    </div>

    <!-- 底部提交栏 -->
    <div class="submit-bar">
      <van-submit-bar
        :price="totalPrice1"
        button-text="立即下单"
        @submit="showOrderDialog"
      >
        <template #tip>
          <van-icon name="info-o" />
          <span class="ml-2">费用明细</span>
        </template>
      </van-submit-bar>
    </div>

    <!-- 订单确认弹窗 -->
    <van-dialog 
    v-model:show="showDialog" 
    title="订单确认" 
    show-cancel-button 
    @confirm="onConfirmOrder">
      <div class="order-info">
          <div class="order-info-item">
            <strong>取件地址:</strong> {{ pickupAddress }}
          </div>
          <div class="order-info-item">
            <strong>收件地址:</strong> {{ deliveryAddress }}
          </div>
          <div class="order-info-item">
            <strong>联系方式:</strong> {{ phoneNumber }}
          </div>
          <div class="order-info-item">
          <div class="flex-container">
            <strong>快递信息:</strong>
            <ul class="package-list">
              <li>小件包裹: {{ packageCount.small }} 个</li>
              <li>中件包裹: {{ packageCount.medium }} 个</li>
              <li>大件包裹: {{ packageCount.large }} 个</li>
            </ul>
          </div>
        </div>
      <div class="order-info-item">
          <strong>取件码:</strong> {{ pickupCode }}
      </div>
      <div class="order-info-item">
          <strong>备注留言:</strong> {{ remarks }}
      </div>
      <div class="order-info-item">
          <strong>金额:</strong> {{ totalPrice }} 元
      </div>
      </div>
    </van-dialog>

    <!-- 地址选择浮层 -->
    <div v-if="isAddressPopupVisible" class="popup-overlay">
      <div class="popup">
        <h3>选择地址</h3>
        <ul>
          <li v-for="address in filteredAddressList"  :key="address.addressType" @click="onSelectAddress(address.address)">
            {{ address.address }}
          </li>
        </ul>
        <button @click="hideAddressPopup" class="closebtn">关闭</button>
      </div>
    </div>
  </div>

  
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { UploaderFileListItem,Dialog,Popup,Picker } from 'vant'
import { useRouter } from 'vue-router'
import { useTokenStore } from '../../stores/Login'
import axios from 'axios'
import { confirmOrder } from '../../api/Order/index'
import { showToast } from 'vant';
import { getUserInfo } from '../../api/Person/index';

interface PackageCount {
  small: number
  medium: number
  large: number
}

// 状态定义
const packageCount = ref<PackageCount>({
  small: 0,
  medium: 0,
  large: 0
})
const pickupCode = ref('')//取件码
const fileList = ref<UploaderFileListItem[]>([])//上传图片
const remarks = ref('')//备注留言
const router = useRouter()
const pickupAddress = ref('');//取件地址
const deliveryAddress = ref('');//收件地址
const phoneNumber = ref('');//联系方式
const otherContact = ref('');//其他联系方式
const showDialog = ref(false);//是否显示对话框
const addressType = ref(2); // 用于区分是取件地址还是送件地址
const addressList = ref([]); // 示例地址列表，可以根据实际情况替换
const isAddressPopupVisible = ref(false); // 用于控制地址选择浮层的显示
const {user} = useTokenStore();
const userId = ref(0);
const totalPrice = ref(0);
const balance = ref(0);

// 从本地存储中获取用户信息
const storedUser = localStorage.getItem("user");
if (storedUser) {
  const user = JSON.parse(storedUser).user; // 解析用户信息
  userId.value = user.userId; // 提取用户 ID
  addressList.value = user.addressArray; // 获取用户地址列表
  balance.value = user.balance; // 获取用户余额
  console.log(userId.value);
}

//返回首页
const goback = () => {
  router.go(-1)
}

// 计算属性
const totalPackages = computed(() => {
  return packageCount.value.small + 
         packageCount.value.medium + 
         packageCount.value.large
})

// 计算总价
const totalPrice1 = computed(() => {
  const basePrice = packageCount.value.small * 100 + 
                   packageCount.value.medium * 300 + 
                   packageCount.value.large * 500
  return basePrice
})

// 自动识别取件码
const verifyCode = async() => {
  if (fileList.value.length === 0) {
    console.error('请先上传图片');
    return;
  }

  const formData = new FormData();
  formData.append('image', fileList.value[0].file); // 将文件附加到 FormData 对象中
  try {
    const response = await axios.post('http://localhost:8080/orders/add/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log('上传成功:', response.data.data);
    if (response.data.data) {
      pickupCode.value = response.data.data; // 将识别得到的取件码填入输入框
    }
  } catch (error) {
    console.error('上传失败:', error);
  }
}

// 上传图片后的回调函数
const onAfterRead = async (file) => {
  fileList.value = [file]; // 将文件保存到 fileList 中
};

// 立即下单
const getReward = async (data) => {
  try {
     const response = await axios.post('http://localhost:8080/orders/add/getReward', data);
     totalPrice.value=response.data.data;
    return response;
  } catch (error) {
    throw error;
  }
};

// 显示订单浮层
const showOrderDialog = async () => {
  const data = {
    customerId: userId.value,
    pickupAddress: pickupAddress.value,
    deliveryAddress: deliveryAddress.value,
    phoneNumber: phoneNumber.value,
    smallNum: packageCount.value.small,
    mediumNum: packageCount.value.medium,
    bigNum: packageCount.value.large,
    description: remarks.value,
    code: pickupCode.value
  };

  console.log('发送的订单数据:', data); // 打印请求数据

  try {
    const response = await getReward(data);
    console.log('响应数据:', response.data); // 打印响应数据
    if (response.data.code === 200) {
      console.log('获取报酬成功:', response.data);
      showDialog.value = true; // 显示对话框
    } else {
      console.error('获取报酬失败:', response.data.msg);
      alert(response.data.msg); // 显示错误信息
    }
  } catch (error) {
    console.error('获取报酬失败:', error);
    alert('获取报酬失败，请稍后重试'); // 显示通用错误信息
  }
};

// 确认订单
const onConfirmOrder = async () => {
  const data = {
    customerId: userId.value,
    pickupAddress: pickupAddress.value,
    deliveryAddress: deliveryAddress.value,
    phoneNumber: phoneNumber.value,
    smallNum: packageCount.value.small,
    mediumNum: packageCount.value.medium,
    bigNum: packageCount.value.large,
    description: remarks.value,
    code: pickupCode.value
  };

  console.log('确认订单:', data);

  try {
    const response = await confirmOrder(data);
    console.log('订单确认成功:', response.data);
    if (response.data.code === 200) {
      showToast({ type: 'success', message: '下单成功' });
      showDialog.value = false; // 关闭对话框
      // 更新本地存储的余额
      
      const storedUser = localStorage.getItem('user');
      if (storedUser) {
        const userData = JSON.parse(storedUser).user;
        userData.balance -= totalPrice.value; // 减少余额
        localStorage.setItem('user', JSON.stringify({ user: userData }));
      }
      router.push('/task');
    } else {
      console.error('订单确认失败:', response.data.msg);
      alert(response.data.msg); // 显示错误信息
    }
    showDialog.value = false; // 关闭对话框
  } catch (error) {
    console.error('订单确认失败:', error);
  }
};

// 打开地址选择浮层
const openAddressPopup = (type: number) => {
  addressType.value = type;
  isAddressPopupVisible.value = true;
};

// 关闭地址选择浮层
const hideAddressPopup = () => {
  isAddressPopupVisible.value = false;
};

// 选择地址
const onSelectAddress = (address: string) => {
  if (addressType.value === 2) {
    pickupAddress.value = address;
  } else if (addressType.value === 1) {
    deliveryAddress.value = address;
  }
  hideAddressPopup();
};

// 选择电话号码
const onSelectPhone = () => {
  const storedUser = localStorage.getItem('user');
  if (storedUser) {
    const userData = JSON.parse(storedUser).user;
    phoneNumber.value = userData.phoneNumber; // 从本地存储中获取最新的电话号码
  } else {
    phoneNumber.value = user.phoneNumber; // 从用户信息中获取电话号码
  }
};

// 过滤地址列表
const filteredAddressList = computed(() => {
  return addressList.value.filter(address => address.addressType === addressType.value);
});

</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.banner {
  background-color: #FD5958;
  padding: 20px;
  text-align: center;
}

.banner-image {
  max-width: 100%;
  height: auto;
}

.banner-return {
  position: absolute;
  top: 30px; /* 调整箭头距离顶部的距离 */
  left: 20px; /* 调整箭头距离左侧的距离 */
  width: 20px; /* 调整箭头的宽度 */
  height: 20px; /* 调整箭头的高度 */
  cursor: pointer;
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.flex-container {
  display: flex;
  align-items: center;
}

.package-list {
  list-style: none;
  padding: 0;
  margin: 0;
  /* display: flex; */
}

.package-list li {
  margin-left: 5px;
}

.order-info {
  padding: 10px;
}

.order-info-item {
  margin-bottom: 10px;
}

.order-info-item strong {
  display: inline-block;
  width: 80px;
}

.common-use{
  background-color: #FF8C00;
  border-radius: 5px;
  height: 25px;
  font-size: 11px;
  text-align: center;
}

.address-info {
  padding: 20px;
  background-color: #fff;
  margin: 5px;
  border: 1px solid #ddd;
}

.qusong-title {
  text-align: center;
  margin-bottom: 10px;
}

.qusong-title h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.qusong-title span {
  font-size: 14px;
  color: #888;
}

.divider {
  border-bottom: 1px dashed #ccc;
  margin: 10px 0;
}

.order-form .header {
  text-align: center;
  margin-bottom: 10px;
}

.order-form .header h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  padding-top: 15px;
}

.order-form .header span {
  font-size: 14px;
  color: #888;
}

.order-form {
  padding-bottom: 50px;
  background-color: #f7f8fa;
  border: 1px solid #ddd;
  margin: 5px;
}

.header {
  height: 70px;
  background-color: #fff;
  margin-bottom: 12px;
}

.subtitle {
  padding: 8px 16px;
  color: #999;
  font-size: 12px;
  text-align: center;
}

.package-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.package-desc {
  font-size: 12px;
  color: #999;
}

.mt-3 {
  margin-top: 12px;
}

.ml-2 {
  margin-left: 8px;
}

.mt-4{
  margin-top: 12px;
  padding-bottom:60px;
}

.total-packages {
  color: #1989fa;
  font-size: 14px;
  text-align: right;
}

.van-submit-bar {
  position: fixed;
  bottom: 61px;
  left: 0;
  right: 0;
}

.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup {
  width: 326px;
  height: 193px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
}

.popup h3 {
  margin-top: 0;
}

.popup ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.popup li {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  cursor: pointer;
}

.popup li:hover {
  background-color: #f5f5f5;
}

.closebtn{
  display: block;
  width: 40%;
  padding: 10px;
  margin-top: 10px;
  background-color: #FD5958;
  color: #fff;
  text-align: center;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  position: absolute;
  left: 30%;
  top:510px;
}
</style>